const express = require('express');
const path = require('path');
const session = require('express-session');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
const config = require('./config.js');
const envConfig = require('./env/config_development');
var refer = require('./../app/socket.io/refer.js');

const mongoose = require('mongoose');

// db connection
if (envConfig.mongodb.debug) {
    mongoose.set('debug', true);
}
var db = mongoose.connect(envConfig.mongodb.uri, envConfig.mongodb.options, function (err) {
    if (err) {
        console.error('Could not connect to MongoDB!');
        console.error(err);
        process.exit(-1);
    }
    else {
        console.log('Connected to MongoDB!');
    }
});

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Powered-By,Content-Type");
    if (req.method === 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
});

// view engine setup
app.set('views', express.static('public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static('public'));

var ses = session({
    secret: envConfig.session_secret,
    resave: true,
    saveUninitialized: true,
});

app.use(ses);

//Cross origin
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With,X-Powered-By,Content-Type");
    if (req.method === 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
});

// Globbing express routing files
config.getGlobbedFiles('app/routes/**/*.js').forEach(function (routePath) {
    // console.log(routePath);
    require(path.resolve(routePath))(router);
});

app.use(envConfig.context, router);


app.use(function(req, res, next) {
    if (envConfig.mongodb.debug && req.cookies['mock_merchant']) {
        var mockMerchant = JSON.parse(req.cookies['mock_merchant']);
        req.session.merchant = new Merchant(mockMerchant);
        return next();
    }
    next();
});

// error handler
app.use(function (err, req, res, next) {
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
});

app.ready=function(server){
    refer.prepareSocketIO(server);
};

exports = module.exports = app;


